package csc.fresher.commons;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletRequest;
import javax.faces.validator.Validator;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

@FacesValidator("csc.fresher.commons.validator")
public class RecaptchaValidator implements Validator {

	  @Override
		public void validate(FacesContext context, UIComponent component, Object value)	throws ValidatorException {
			HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
			RecaptchaComponent c = (RecaptchaComponent) component;
			String remoteAddr = request.getRemoteAddr();
			ReCaptchaImpl reCaptcha = new ReCaptchaImpl();

			
			String privateKey = null;
			privateKey = c.getPrivateKey();
			
			reCaptcha.setPrivateKey(privateKey);

			String challenge = request.getParameter("recaptcha_challenge_field");
			String uresponse = request.getParameter("recaptcha_response_field");
			ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr,	challenge, uresponse);

			if (!reCaptchaResponse.isValid()) {
				throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid captcha", "Invalid captcha"));
			}
		}
}
